//
//  TopicDetailController.m
//  QQplayground
//
//  Created by zhangxy on 2018/7/4.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "TopicDetailController.h"


#import <SDWebImage/UIImageView+WebCache.h>
#import "UserInfoController.h"
#import "ZZProgressVIew.h"
#import "ZZShareView.h"

#import "ZZHomeListCell.h"
#define cellIdentifier @"ZZHomeListCell"

#import "ZZContentDetailController.h"
#import "ZZContentCommentController.h"
#import "MyButton.h"
#import <MJRefresh.h>

@interface TopicDetailController ()<ZZTopicCellDelegate>{
    int Space;
    int  page;
    
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  NSArray *headerArr;
@property(nonatomic,strong)  UITableView *listTable;


@property(nonatomic,strong)  UIView *headerView;
@property(nonatomic,strong)  UIView *footerView;

@property(nonatomic,strong)  UIImageView *imgHeader;
@property(nonatomic,strong)  UILabel *labTitle;
@property(nonatomic,strong)  UILabel *labTime;
@property(nonatomic,strong)  UILabel *labDesc;

@property(nonatomic,strong)  UILabel *labDepartment;
@property(nonatomic,strong)  UILabel *labName;
@property(nonatomic,strong)  UIImageView *imgAvatar;
@property(nonatomic,strong)  ZZProgressVIew *progressGoodView;
@property(nonatomic,strong)  ZZProgressVIew *progressBadView;
@property(nonatomic,strong)  UIButton *btnShare;

@end

@implementation TopicDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [super viewDidLoad];
    self.navigationItem.title = @"专题";
    [self setNavigationBar];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_sharenew"] style:UIBarButtonItemStylePlain target:self action:@selector(tapClick)];
    
    
    self.navigationController.navigationBarHidden = NO;
    
    Space = 30;
    
    [self createTableView];
    
    
//    MJRefreshFooter *footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
//        [self loadMoreData];
//    }];
//    _listTable.footer = footer;
    page = 1;
    [self loadMoreData];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}


-(void)OnClickAddvote:(NSString  *) type{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_model.s_id forKey:@"id"];
    [params setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
    [params setObject:convertToString(type) forKey:@"type"];
    
    [NetworkUtil POST:API_GetSpecialAddvote parameters:params success:^(id responseObject, NSDictionary *dict) {
        
        [PopUtil showMessage:convertToString(dict[@"msg"])];
        CGFloat f = 0;
        if([@"like" isEqual:type]){
            self.model.like_count = dict[@"data"][@"count"];
            CGFloat like = [_model.like_count floatValue];
            CGFloat drop = [_model.drop_count floatValue];
            CGFloat view_count = like + drop;//[_model.view_count floatValue];
            f = [self.model.like_count floatValue]/view_count;//[self.model.view_count floatValue];
            if(f>1){
                f = 1;
            }
            
            [self.progressGoodView changeValue:@{@"value":[NSString stringWithFormat:@"%0.2f",f],@"title":@"加鸡腿",@"icon":@"个人页点赞"}];
        }else{
            self.model.drop_count = dict[@"data"][@"count"];
            CGFloat like = [_model.like_count floatValue];
            CGFloat drop = [_model.drop_count floatValue];
            CGFloat view_count = like + drop;//[_model.view_count floatValue];
            f = [self.model.drop_count floatValue]/view_count;[self.model.view_count floatValue];
            if(f>1){
                f = 1;
            }
         
            [self.progressBadView changeValue:@{@"value":[NSString stringWithFormat:@"%0.2f",f],@"title":@"扣工资",@"icon":@"个人页点赞"}];
        }
    } failure:^(NSError *error, NSString *message) {
        [PopUtil showMessage:convertToString(message)];
    }];
}


/**
 加载更多
 */
-(void)loadMoreData{
    NSString *api = API_GetSpeciaDetail;
    
    NSDictionary *p = @{@"id":_model.s_id,@"page":convertIntToString(page)};
    
    [NetworkUtil POST:api parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        
        if(page == 1){
            self->_model = [[SpecialEntity alloc] initWithDictionary:dictionary[@"data"]];
            _listTable.tableHeaderView = [self createTableHeaderView];
            _listTable.tableFooterView = [self createFooterView];
             [self.listArray removeAllObjects];
            
            
            [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(_model.author_user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
        }
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                
                ZZHomeTopicEntity *model = [[ZZHomeTopicEntity alloc] initWithDictionary:item];
                model.nav_type = self->_model.nav_type;
                [self.listArray addObject:model];
            }
            
        }
        [self.listTable reloadData];
        if(arr.count > 0){
            page = page + 1;
        }
        
    } failure:^(NSError *error, NSString *message) {
        [PopUtil showMessage:message];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}


-(UIView *)createTableHeaderView{
    _headerView = [[UIView alloc] init];
    
    _imgHeader = [self createImageView];
    [_imgHeader setFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    
    [_imgHeader sd_setImageWithURL:[NSURL URLWithString:convertToString(_model.image_url)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    
    _labTitle = [self createLabel];
    [_labTitle setFont:FontSeventeen];
    [_labTitle setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [_labTitle setFrame:CGRectMake(20, CGRectGetMaxY(_imgHeader.frame) + 20, ScreenWidth - 140, 0)];
    [_labTitle setText:convertToString(_model.title)];

    [self autoWidthOfLabelHegith:_labTitle with:_labTitle.frame.size.width];
    
    _labTime = [self createLabel];
    [_labTime setFont:FontThirteen];
    [_labTime setTextColor:UIColorFromRGB(TextSizeEightColor)];
    [_labTime setTextAlignment:NSTextAlignmentRight];
    [_labTime setFrame:CGRectMake(ScreenWidth-120, CGRectGetMaxY(_imgHeader.frame) + 20, 100, 24)];
    [_labTime setText:convertToString(_model.add_time)];
    
    _labDesc = [self createLabel];
    [_labDesc setFrame:CGRectMake(20, CGRectGetMaxY(_labTitle.frame) + Space, ScreenWidth - 140, 0)];
    [_labDesc setText:convertToString(_model.intro)];
#warning - 显示HTML文本在label
    NSMutableAttributedString *labTitle = [[NSMutableAttributedString alloc] initWithData:[_model.intro dataUsingEncoding:NSUnicodeStringEncoding]
                                                                                  options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                                                                       documentAttributes:nil
                                                                                    error:nil];
    [labTitle addAttribute:NSFontAttributeName value:FontFiftent range:NSMakeRange(0, labTitle.length)];
    [labTitle addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(TextSizeOneColor) range:NSMakeRange(0, labTitle.length)];
    _labDesc.attributedText = labTitle;
    
    [self autoWidthOfLabelHegith:_labDesc with:_labDesc.frame.size.width];
    
    
    [_headerView addSubview:_imgHeader];
    [_headerView addSubview:_labTitle];
    [_headerView addSubview:_labTime];
    [_headerView addSubview:_labDesc];
    
    [_headerView setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_labDesc.frame))];
    
    return _headerView;
    
    
}

-(UIView *)createFooterView{
    _footerView = [[UIView alloc] init];
    
    _labDepartment = [self createLabel];
    [_labDepartment setFont:FontThirteen];
    [_labDepartment setTextColor:UIColorFromRGB(Text6Color)];
    [_labDepartment setFrame:CGRectMake(20, Space, ScreenWidth - 40, 18)];
    [_labDepartment setText:convertToString(@"值班小编")];
    
    _imgAvatar = [self createImageView];
    [_imgAvatar setFrame:CGRectMake(20, CGRectGetMaxY(_labDepartment.frame)+ Space, 44, 44)];
    _imgAvatar.layer.cornerRadius = 22.0f;
    _imgAvatar.layer.masksToBounds = YES;
    [_imgAvatar setImage:[UIImage imageNamed:@"default_image"]];
//    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(_model.author_user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    
    _labName = [self createLabel];
    [_labName setFont:FontSeventeen];
    [_labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [_labName setFrame:CGRectMake(20 + 44 + 10,  CGRectGetMaxY(_labDepartment.frame)+Space, ScreenWidth - 94, 44)];
    [_labName setText:convertToString(_model.author_user_info.user_name)];
    
    CGFloat like = [_model.like_count floatValue];
    CGFloat drop = [_model.drop_count floatValue];
    CGFloat view_count = like + drop;//[_model.view_count floatValue];
    NSString *likeStr = [NSString stringWithFormat:@"%.2f",like/view_count];
    NSString *dropStr = [NSString stringWithFormat:@"%.2f",drop/view_count];
    
    _progressGoodView = [[ZZProgressVIew alloc] initWithBgColor:UIColorFromRGB(0xFFADCC) tintColor:UIColorFromRGB(0xFF70A6) frame:CGRectMake(74, CGRectGetMaxY(_labName.frame) + 15, ScreenWidth - 94, 44) value:@{@"value":likeStr,@"title":@"加鸡腿",@"icon":@"个人页点赞"}];
    [_progressGoodView setOnItemClickBlock:^(ZZProgressViewType clickType, NSString *title) {
        [self OnClickAddvote:@"like"];
    }];
    
    _progressBadView = [[ZZProgressVIew alloc] initWithBgColor:UIColorFromRGB(0xFFADCC) tintColor:UIColorFromRGB(0xFF70A6) frame:CGRectMake(74, CGRectGetMaxY(_progressGoodView.frame) + 15, ScreenWidth - 94, 44) value:@{@"value":dropStr,@"title":@"扣工资",@"icon":@"个人页点赞"}];
    [_progressBadView setOnItemClickBlock:^(ZZProgressViewType clickType, NSString *title) {
        [self OnClickAddvote:@"drop"];
    }];
    
    
    [_footerView addSubview:_labDepartment];
    [_footerView addSubview:_labName];
    [_footerView addSubview:_progressGoodView];
    [_footerView addSubview:_progressBadView];
    [_footerView addSubview:_imgAvatar];
    
    [_footerView setFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_progressBadView.frame))];
    
    return _footerView;
}


-(UIImageView *)createImageView{
    UIImageView *imgView = [[UIImageView alloc] init];
    [imgView setContentMode:UIViewContentModeScaleAspectFill];
    imgView.clipsToBounds = YES;
    return imgView;
}

-(UILabel *) createLabel{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setTextAlignment:NSTextAlignmentLeft];
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setNumberOfLines:0];
    return label;
}

-(UIButton *) createButton{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn.titleLabel setFont:FontFiftent];
    return btn;
}


-(void)tapClick{
    ZZShareView *share = [[ZZShareView alloc] initWithShareType:ZZShareTypeSpecial vc:self obj:_model];
    [share show];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    [self setTableSeparatorInset];
    
    
//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self loadBegin];
//    }];
//    header.stateLabel.hidden=YES;
//    header.lastUpdatedTimeLabel.hidden=YES;
//    _listTable.header = header;
    
    
    _listTable.tableHeaderView = [self createTableHeaderView];
    _listTable.tableFooterView = [self createFooterView];
}


-(void)loadBegin{
    page = 1;
    [self loadMoreData];
}



-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}

#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1.0f;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    return headerView;
}


// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZHomeListCell *cell = (ZZHomeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZHomeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.delegate = self;
    [cell dataToView:[_listArray objectAtIndex:indexPath.row]];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZZHomeTopicEntity *model=[_listArray objectAtIndex:indexPath.row];
    ZZContentDetailController *vc = [[ZZContentDetailController alloc] init];
    vc.entity = model;
    [self openPushVC:vc];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.section+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint vel = [scrollView.panGestureRecognizer velocityInView:scrollView];
    if(vel.y < 0){
        // 上拉
        
    }else{
        
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}



#pragma mark UITableView delegate end
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
